import React, {Component} from 'react';
import {nanoid} from 'nanoid'
import PropTypes from 'prop-types'

export default class Header extends Component {
  // 利用prop-types库对传递的标签属性进行类型以及必要性的限制
  static propTypes = {
    addTodo: PropTypes.func.isRequired,
  }

  handleKeyUp = (event) => {
    // keyCode是键盘上按键的标识
    const {keyCode, target} = event;
    // 13是回车键的标识，按下回车键，获取输入框的值
    if(keyCode !== 13) return
    // 添加的todo名不能为空
    if(target.value.trim() === '') {
      alert('输入不能为空')
      return
    }
    // 子组件给父组件传值
    const todoObj = {
      id: nanoid(),
      name: target.value,
      done: false,
    }
    this.props.addTodo(todoObj)
    // 清空输入值
    target.value = ''
  }
  render() {
    return (
      <div>
        <div className="todo-header">
          <input type="text" placeholder='请输入你的任务名称，按回车键确认' onKeyUp={this.handleKeyUp} />
        </div>
      </div>
    )
  }
}
